package com.wx.wxpush.util;

import com.google.common.collect.Lists;
import com.wx.wxpush.entiy.Tree;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {
    private List<Tree> rootList; // 根节点对象存放到这里

    private List<Tree> bodyList; // 其他节点存放到这里，可以包含根节点

    public TreeUtil(List<Tree> rootList, List<Tree> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    public List<Tree> getTree() { // 调用的方法入口
        if (bodyList != null && !bodyList.isEmpty()) {
            // 声明一个map，用来过滤已操作过的数据
            Map<String, String> map = new HashMap<>();
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return null;
    }

    public void getChild(Tree beanTree, Map<String, String> map) {
        List<Tree> childList = Lists.newArrayList();
        //map.containsKey()判断map中key是否存在，存在返回true 不存在返回false，！相反
        bodyList.stream().filter(c -> !map.containsKey(c.getRoleCode())).filter(c -> c.getSuperiorUnit().equals(beanTree.getRoleCode()))
                .forEach(c -> {
                    map.put(c.getRoleCode(), c.getSuperiorUnit());
                    getChild(c, map);
                    childList.add(c);
                });
        beanTree.setChilds(childList);
    }
}
